package org.jeecg.modules.system.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.entity.ContentType;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.UpDocumentTypeConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.*;
import org.jeecg.modules.third.aipocr.AipOcrService;
import org.jeecg.modules.third.aliyunocr.AliyunOcrService;
import org.jeecg.modules.third.huaweiocr.HuaweiOcrService;
import org.jeecg.modules.third.huaweiocr.constant.HuaweiOcrConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.ModelAndView;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.util.Date;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @Author scott
 * @since 2018-12-20
 */
@Slf4j
@RestController
@RequestMapping("/sys/common")
public class CommonController {

    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;
    @Value(value = "${jeecg.path.bank}")
    private String bankpath;
    /**
     * 本地：local minio：minio 阿里：alioss
     */
    @Value(value="${jeecg.uploadType}")
    private String uploadType;

    private   String imgName = "";


    @Autowired
    private AipOcrService aipOcrService;

    @Autowired
    private AliyunOcrService aliyunOcrService;

    @Autowired
    private HuaweiOcrService huaweiOcrService;

    /**
     * @Author 政辉
     * @return
     */
    @GetMapping("/403")
    public Result<?> noauth()  {
        return Result.error("没有权限，请联系管理员授权");
    }

    /**
     * 文件上传统一方法
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "/upload")
    public Result<?> upload(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Result<?> result = new Result<>();
        String savePath = "";
        String bizPath = request.getParameter("biz");
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        // 获取上传文件对象
        MultipartFile file = multipartRequest.getFile("file");
        if(oConvertUtils.isEmpty(bizPath)){
            if(CommonConstant.UPLOAD_TYPE_OSS.equals(uploadType)){
                //未指定目录，则用阿里云默认目录 upload
                bizPath = "upload"  + File.separator + DateUtils.getDate("yyyyMMdd");
                //result.setMessage("使用阿里云文件上传时，必须添加目录！");
                //result.setSuccess(false);
                //return result;
            }else{
                //bizPath = "";
                bizPath = "temp" + File.separator + DateUtils.getDate("yyyyMMdd");
            }
        }else {
            bizPath = bizPath + File.separator + DateUtils.getDate("yyyyMMdd");
        }
        if(CommonConstant.UPLOAD_TYPE_LOCAL.equals(uploadType)){
            //针对jeditor编辑器如何使 lcaol模式，采用 base64格式存储
            String jeditor = request.getParameter("jeditor");
            if(oConvertUtils.isNotEmpty(jeditor)){
                result.setMessage(CommonConstant.UPLOAD_TYPE_LOCAL);
                result.setSuccess(true);
                return result;
            }else{
                //是图片类型并大小大于500kb  压缩
               int fileSize = (int)(file.getSize() / 1024)+1;
               if(ImageCompressUtil.checkType(file.getOriginalFilename()) && fileSize > 500 ) {
                   savePath =  getCompressPic(bizPath, file);
               }else {
                   savePath = this.uploadLocal(file,bizPath);
               }
            }
        }else{
            //update-begin-author:taoyan date:20200814 for:文件上传改造
            savePath = CommonUtils.upload(file, bizPath, uploadType);
            //update-end-author:taoyan date:20200814 for:文件上传改造
        }

        if(oConvertUtils.isNotEmpty(savePath)){
            result.setMessage(savePath);
            result.setSuccess(true);
        }else {
            result.setMessage("上传失败！");
            result.setSuccess(false);
        }
        return result;
    }

    private void checkImgSize(String savePath) {
        if(StringUtils.isNotEmpty(savePath) ){
            String savePathTmp =  uploadpath  + File.separator +savePath;
            String type = ImageCompressUtil.getMimeType(savePathTmp);
            if(StringUtils.isNotEmpty(type) && type.contains("image")){
                File file = new File(savePathTmp);
                if(file.length()/1024 > 1024*8){
                    throw new JeecgBootException("你上传的图片超过8M，请上传小于8M以内的图片");// 大于50K，
                }
            }
        }
    }

    @PostMapping(value = "/whly/uploadImg")
    public Result<?> whlyUpload(HttpServletRequest request, HttpServletResponse response) throws IOException {

//        String contentType = request.getContentType();  //获取Content-Type
//        if(!contentType.contains("image/")){
//            throw new JeecgBootException("请上传图片");
//        }
        Result <JSONObject> result = new Result <>();
        JSONObject jsonObject = new JSONObject();
        String savePath = "";
        String bizPath = request.getParameter("biz");
        String upType = request.getParameter("upDocumentType");
        String side = request.getParameter("side");
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        // 获取上传文件对象
        MultipartFile file = multipartRequest.getFile("file");

        if(!ImageCompressUtil.checkType(file.getOriginalFilename())){
            throw new JeecgBootException("请上传图片类型");
        }

        if(oConvertUtils.isEmpty(bizPath)){
            bizPath = "wlhy" +File.separator + DateUtils.getDate("yyyyMMdd");
        }else{
            bizPath =  "temp" +File.separator + DateUtils.getDate("yyyyMMdd");
        }
        if(CommonConstant.UPLOAD_TYPE_LOCAL.equals(uploadType)){
            //针对jeditor编辑器如何使 lcaol模式，采用 base64格式存储
            String jeditor = request.getParameter("jeditor");
            if(oConvertUtils.isNotEmpty(jeditor)){
                result.setMessage(CommonConstant.UPLOAD_TYPE_LOCAL);
                result.setSuccess(true);
                return result;
            }else{
                int fileSize = (int)(file.getSize() / 1024)+1;
                if(fileSize <= 500){
                    savePath = this.uploadLocal(file,bizPath);
                }else{
                    savePath =  getCompressPic(bizPath, file);
                }
               // checkImgSize(savePath);
                side = StringUtils.isNotBlank(side)?side:"";
                jsonObject = this.getAipOcrResources(savePath,upType ,side);
            }
        }else{
            //update-begin-author:taoyan date:20200814 for:文件上传改造
            savePath = CommonUtils.upload(file, bizPath, uploadType);
            String jsonString = aipOcrService.webImage(savePath);
            jsonObject = JSONObject.parseObject(jsonString);
            //update-end-author:taoyan date:20200814 for:文件上传改造
        }
        if(oConvertUtils.isNotEmpty(savePath)){
            if(!jsonObject.isEmpty()){
                result.setResult(jsonObject);
            }
            result.setMessage(savePath);
            result.setSuccess(true);
        }else {
            result.setMessage("上传失败！");
            result.setSuccess(false);
        }
        return result;
    }

    @PostMapping(value = "/whly/uploadPic")
    public Result<?> whlyUploadPic(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        String contentType = request.getContentType();  //获取Content-Type
//        if(!contentType.contains("image/")){
//            throw new JeecgBootException("请上传图片");
//        }
        Result <JSONObject> result = new Result <>();
        JSONObject jsonObject = new JSONObject();
        String savePath = "";
        String bizPath = request.getParameter("biz");
        String upType = request.getParameter("upDocumentType");
        String side = request.getParameter("side");
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        // 获取上传文件对象
        MultipartFile file = multipartRequest.getFile("file");
        if(!ImageCompressUtil.checkType(file.getOriginalFilename())){
            throw new JeecgBootException("请上传图片类型");
        }
        if(oConvertUtils.isEmpty(bizPath)){
            bizPath = "wlhy" +File.separator + DateUtils.getDate("yyyyMMdd");
        }else{
            bizPath =  "temp" +File.separator + DateUtils.getDate("yyyyMMdd");
        }
        if(CommonConstant.UPLOAD_TYPE_LOCAL.equals(uploadType)){
            //针对jeditor编辑器如何使 lcaol模式，采用 base64格式存储
            String jeditor = request.getParameter("jeditor");
            if(oConvertUtils.isNotEmpty(jeditor)){
                result.setMessage(CommonConstant.UPLOAD_TYPE_LOCAL);
                result.setSuccess(true);
                return result;
            }else{
                int fileSize = (int)(file.getSize() / 1024)+1;
                if(fileSize <= 500){
                    savePath = this.uploadLocal(file,bizPath);
                }else{
                    savePath =  getCompressPic(bizPath, file);
                }

                side = StringUtils.isNotBlank(side)?side:"";
                jsonObject = this.getAipOcrResources(savePath,upType,side);

            }
        }else{
            //update-begin-author:taoyan date:20200814 for:文件上传改造
            savePath = CommonUtils.upload(file, bizPath, uploadType);
            String jsonString = aipOcrService.webImage(savePath);
            jsonObject = JSONObject.parseObject(jsonString);
            //update-end-author:taoyan date:20200814 for:文件上传改造
        }
        if(oConvertUtils.isNotEmpty(savePath)){
            if(!jsonObject.isEmpty()){
                result.setResult(jsonObject);
            }
            result.setMessage(savePath);
            result.setSuccess(true);
        }else {
            result.setMessage("上传失败！");
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * 压缩图片
     * @param bizPath
     * @param file
     * @return
     * @throws IOException
     */
    private String getCompressPic(String bizPath, MultipartFile file) throws IOException {
//        int fileSize = (int)(file.getSize() / 1024)+1;
//        float quality = 1F;
//        if(fileSize <= 600){
//            quality = 0.8F;
//        }else if(fileSize <= 800){
//            quality = 0.6F;
//        }else if(fileSize <= 1000){
//            quality = 0.4F;
//        }else{
//            quality = 0.25F;
//        }

//        byte[] imgBytes = ImageCompressUtil.compressPicForScale(file.getBytes(), quality );
//        String imgBase64 =   Base64.encodeBase64String(imgBytes);

        BASE64Decoder decoder = new BASE64Decoder();
        try {
            String savePathTemp = this.uploadLocal(file,bizPath);
            String imgBase64 = ImageUtil.compressImgToBase64(uploadpath + File.separator +savePathTemp, 1024, 768, 1024 * 1024);

            // Base64解码
            byte[] b = decoder.decodeBuffer(imgBase64);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据
                    b[i] += 256;
                }
            }
            //将byte转换为文件
            // 生成图片路径和文件名
            String ctxPath = uploadpath;
            String fileName = null;
            File files = new File(ctxPath + File.separator + bizPath + File.separator );
            if (!files.exists()) {
                files.mkdirs();// 创建文件根目录
            }

            String orgName = file.getOriginalFilename();// 获取文件名
            orgName = CommonUtils.getFileName(orgName);

            if(orgName.indexOf(".") != -1){
                fileName = "compress_"+orgName.substring(0, orgName.lastIndexOf(".")) + "_" + imgName  + orgName.substring(orgName.indexOf("."));
            }else{
                fileName = "compress_" +  imgName  + orgName;
            }
            String savePath = files.getPath() + File.separator + fileName;

            FileOutputStream out = new FileOutputStream(savePath);
            out.write(b);
            out.flush();
            out.close();

            String dbpath = null;
            if(oConvertUtils.isNotEmpty(bizPath)){
                dbpath = bizPath + File.separator + fileName;
            }else{
                dbpath = fileName;
            }
            if (dbpath.contains("\\")) {
                dbpath = dbpath.replace("\\", "/");
            }
            return dbpath;
        }catch(Exception e) {
            System.out.println(e.getMessage());
        }
        return StringUtils.EMPTY;
    }


    @PostMapping(value = "/whly/uploadImgBase64")
    public Result<?> doPost(@RequestBody JSONObject  object,HttpServletRequest request, HttpServletResponse resp){
        Result <JSONObject> result = new Result <>();
        String imageBase64  = object.get("imageBase64").toString();
        String[] split = imageBase64.split(",");
        String img2=split[1];
        BASE64Decoder decoder = new BASE64Decoder();
        try{
            // Base64解码
            byte[] b = decoder.decodeBuffer(img2);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据
                    b[i] += 256;
                }
            }
            //将byte转换为文件
            // 生成图片路径和文件名
            String l = String.valueOf(System.currentTimeMillis());
            String pathString = uploadpath+"/"+l+".jpg";

            FileOutputStream  out = new FileOutputStream(pathString);
            out.write(b);
            out.flush();
            out.close();
//            System.out.println("生成图片结束");


            File file  = new File(pathString);

            InputStream inputStream = new FileInputStream(file);
            MultipartFile multipartFile = new MockMultipartFile(file.getName(), file.getName(),
                    ContentType.APPLICATION_OCTET_STREAM.toString(), inputStream);

            JSONObject jsonObject = new JSONObject();
            String savePath = "";
            String bizPath ="";
            String upType = "";
            String side = "";
            if(oConvertUtils.isEmpty(bizPath)){
                bizPath = "wlhy" +File.separator + DateUtils.getDate("yyyyMMdd");
            }else{
                bizPath =  "temp" +File.separator + DateUtils.getDate("yyyyMMdd");
            }
            if(CommonConstant.UPLOAD_TYPE_LOCAL.equals(uploadType)){
                //针对jeditor编辑器如何使 lcaol模式，采用 base64格式存储
                String jeditor = request.getParameter("jeditor");
                if(oConvertUtils.isNotEmpty(jeditor)){
                    result.setMessage(CommonConstant.UPLOAD_TYPE_LOCAL);
                    result.setSuccess(true);
                    return result;
                }else{
                    savePath = this.uploadLocal(multipartFile,bizPath);
                    //checkImgSize(savePath);
                    side = StringUtils.isNotBlank(side)?side:"";
                    jsonObject = this.getAipOcrResources(savePath, upType ,side);
                }
            }else{
                //update-begin-author:taoyan date:20200814 for:文件上传改造
                savePath = CommonUtils.upload(multipartFile, bizPath, uploadType);
                String jsonString = aipOcrService.webImage(savePath);
                jsonObject = JSONObject.parseObject(jsonString);
                //update-end-author:taoyan date:20200814 for:文件上传改造
            }
            if(oConvertUtils.isNotEmpty(savePath)){
                if(!jsonObject.isEmpty()){
                    result.setResult(jsonObject);
                }
                result.setMessage(savePath);
                result.setSuccess(true);
            }else {
                result.setMessage("上传失败！");
                result.setSuccess(false);
            }
            return result;

        } catch (Exception e) {

        }
        return result;

    }


    /**
     * 获取AipOcr文字识别资源
     * @param savePath
     * @param upType
     * @param side 如果upType是身份证类型需要传该字段 side:front正面 ;back背面
     * @return
     */
    @SneakyThrows
    private JSONObject getAipOcrResources(String savePath ,String upType,String side)  {
//        Objects.requireNonNull(savePath);
//        Objects.requireNonNull(upType);
        if(StringUtils.isEmpty(savePath) || StringUtils.isEmpty(upType)){
            return new JSONObject();
        }

        String file = uploadpath+File.separator+savePath;
        String jsonString = "";
        switch (upType){
            case UpDocumentTypeConstant.DOCUMENT_TYPE_IDCARD:
                if(StringUtils.isNotEmpty(side)){
                    side = side.equals("front") ? "face": "back";
                    jsonString =  aliyunOcrService.ocrIdcard(file,side);

//                    String resourcesString =  aipOcrService.idCard(file,side);
//                    //身份证正面时判断图片状态是否正常
//                    if(side.equals("front")){
//                        JSONObject jsonObject = JSONObject.parseObject(resourcesString);
//                        String  imageStatus = jsonObject.get("image_status").toString();
//                        String  riskType = jsonObject.get("risk_type").toString();
//                        if(StringUtils.isNotEmpty(imageStatus) && imageStatus.equals("normal") &&
//                                StringUtils.isNotEmpty(riskType) && riskType.equals("normal") ){
//                            jsonString = resourcesString;
//                        }
//                    }else{
//                        jsonString = resourcesString;
//                    }
                }
                break;
            case UpDocumentTypeConstant.DOCUMENT_TYPE_BANKCARD:
//                    jsonString =  aipOcrService.bankCard(file);
                String httpUrl = huaweiOcrService.getURL(HuaweiOcrConstant.URL_PATH_BANKCARD);
                jsonString=  huaweiOcrService.getInfoByAKSK( file , httpUrl, "");
                break;
            case UpDocumentTypeConstant.DOCUMENT_TYPE_DRIVINGLICENSE:
                if(StringUtils.isNotEmpty(side)) {
                    String httpUri = huaweiOcrService.getURL(HuaweiOcrConstant.URL_PATH_DRIVER_LICENSE);
                    jsonString=  huaweiOcrService.getInfoByAKSK( file , httpUri, side);
//                    side = side.equals("front") ? "face" : "back";
//                    jsonString = aliyunOcrService.ocrDriver(file, side);
                }
                //jsonString =  aipOcrService.drivingLicense(file);
                break;
            case UpDocumentTypeConstant.DOCUMENT_TYPE_VEHICLELICENSE:
                if(StringUtils.isNotEmpty(side)) {
                    String httpUri = huaweiOcrService.getURL(HuaweiOcrConstant.URL_PATH_VEHICLE_LICENSE);
                    jsonString=  huaweiOcrService.getInfoByAKSK( file , httpUri, side);
//                    side = side.equals("front") ? "face" : "back";
//                    jsonString = aliyunOcrService.ocrVehicle(file, side);
                   // jsonString = aipOcrService.vehicleLicense(file, side);
                }
                break;
            case UpDocumentTypeConstant.DOCUMENT_TYPE_PLATELICENSE:
                jsonString =  aipOcrService.plateLicense(file);
                break;
            case UpDocumentTypeConstant.DOCUMENT_TYPE_BUSINESSLICENSE:
//                jsonString =  aipOcrService.businessLicense(file);
                String httpUrl1 = huaweiOcrService.getURL(HuaweiOcrConstant.URL_PATH_BUSINESS_LICENSE);
                jsonString=  huaweiOcrService.getInfoByAKSK( file , httpUrl1, "");
                break;
            case UpDocumentTypeConstant.DOCUMENT_TYPE_TRANSPORTATION_LICENSE:
                String httpUri = huaweiOcrService.getURL(HuaweiOcrConstant.URL_PATH_TRANSPORTATION_LICENSE);
                jsonString=  huaweiOcrService.getInfoByAKSK( file , httpUri, "");
                break;
            case UpDocumentTypeConstant.QUALIFICATIONIMG:
                String httpUri1 = huaweiOcrService.getURL(HuaweiOcrConstant.TRANSPORTATION_QUALIFICATION_CERTIFICATE);
                jsonString=  huaweiOcrService.getInfoByAKSK( file , httpUri1, "");
                break;
            default:
                jsonString =  aipOcrService.basicAccurateGeneral(file);
        }
        return StringUtils.isNotEmpty(jsonString)  ? JSONObject.parseObject(jsonString) : new JSONObject();
    }


    /**
     * 本地文件上传
     * @param mf 文件
     * @param bizPath  自定义路径
     * @return
     */
    private String uploadLocal(MultipartFile mf,String bizPath){
        try {
            String ctxPath = uploadpath;
            String fileName = null;
            File file = new File(ctxPath + File.separator + bizPath + File.separator );
            if (!file.exists()) {
                file.mkdirs();// 创建文件根目录
            }
            String orgName = mf.getOriginalFilename();// 获取文件名
            orgName = CommonUtils.getFileName(orgName);
            imgName = DateUtils.dateToStringDateTime(new Date());
            if(orgName.indexOf(".") != -1){
                fileName = "original_"+orgName.substring(0, orgName.lastIndexOf(".")) + "_" + imgName  + orgName.substring(orgName.indexOf("."));
            }else{
                fileName = "original_" + imgName  + orgName;
            }

            String savePath = file.getPath() + File.separator + fileName;
            File savefile = new File(savePath);
            FileCopyUtils.copy(mf.getBytes(), savefile);
            String dbpath = null;
            if(oConvertUtils.isNotEmpty(bizPath)){
                dbpath = bizPath + File.separator + fileName;
            }else{
                dbpath = fileName;
            }
            if (dbpath.contains("\\")) {
                dbpath = dbpath.replace("\\", "/");
            }
            return dbpath;
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return "";
    }

//	@PostMapping(value = "/upload2")
//	public Result<?> upload2(HttpServletRequest request, HttpServletResponse response) {
//		Result<?> result = new Result<>();
//		try {
//			String ctxPath = uploadpath;
//			String fileName = null;
//			String bizPath = "files";
//			String tempBizPath = request.getParameter("biz");
//			if(oConvertUtils.isNotEmpty(tempBizPath)){
//				bizPath = tempBizPath;
//			}
//			String nowday = new SimpleDateFormat("yyyyMMdd").format(new Date());
//			File file = new File(ctxPath + File.separator + bizPath + File.separator + nowday);
//			if (!file.exists()) {
//				file.mkdirs();// 创建文件根目录
//			}
//			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
//			MultipartFile mf = multipartRequest.getFile("file");// 获取上传文件对象
//			String orgName = mf.getOriginalFilename();// 获取文件名
//			fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.indexOf("."));
//			String savePath = file.getPath() + File.separator + fileName;
//			File savefile = new File(savePath);
//			FileCopyUtils.copy(mf.getBytes(), savefile);
//			String dbpath = bizPath + File.separator + nowday + File.separator + fileName;
//			if (dbpath.contains("\\")) {
//				dbpath = dbpath.replace("\\", "/");
//			}
//			result.setMessage(dbpath);
//			result.setSuccess(true);
//		} catch (IOException e) {
//			result.setSuccess(false);
//			result.setMessage(e.getMessage());
//			log.error(e.getMessage(), e);
//		}
//		return result;
//	}

    private void viewByPath(HttpServletRequest request, HttpServletResponse response, String pathSubfix){
        // ISO-8859-1 ==> UTF-8 进行编码转换
        String imgPath = extractPathFromPattern(request);
        if(oConvertUtils.isEmpty(imgPath) || imgPath=="null"){
            return;
        }
        // 其余处理略
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            imgPath = imgPath.replace("..", "");
            if (imgPath.endsWith(",")) {
                imgPath = imgPath.substring(0, imgPath.length() - 1);
            }

            String filePath = pathSubfix + File.separator + imgPath;
            File file = new File(filePath);
            if(!file.exists()){
                response.setStatus(404);
                log.error("文件:" + filePath + "不存在");
                return;
//                throw new RuntimeException("文件:" + filePath + "不存在");
            }
            response.setContentType("application/force-download");// 设置强制下载不打开
            response.addHeader("Content-Disposition", "attachment;fileName=" + new String(file.getName().getBytes("UTF-8"),"iso-8859-1"));

            inputStream = new BufferedInputStream(new FileInputStream(filePath));
            outputStream = response.getOutputStream();

            byte[] buf = new byte[1024];
            int len;
            while ((len = inputStream.read(buf)) > 0) {
                outputStream.write(buf, 0, len);
            }
            response.flushBuffer();
        } catch (Exception e) {
            log.error("预览文件失败:{}, {}",imgPath, e.getMessage());
            response.setStatus(404);
//            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
    }
    /**
     * 预览图片&下载文件
     * 请求地址：http://localhost:8080/common/static/{user/20190119/e1fe9925bc315c60addea1b98eb1cb1349547719_1547866868179.jpg}
     *
     * @param request
     * @param response
     */
    @GetMapping(value = "/static/**")
    public void view(HttpServletRequest request, HttpServletResponse response) {
        this.viewByPath(request, response, uploadpath);
    }
    /**
     * 预览银行回单pdf
     * 请求地址：http://localhost:8080/common/bank/{user/20190119/e1fe9925bc315c60addea1b98eb1cb1349547719_1547866868179.jpg}
     *
     * @param request
     * @param response
     */
    @GetMapping(value = "/bank/**")
    public void viewBankHd(HttpServletRequest request, HttpServletResponse response) {
        this.viewByPath(request, response, bankpath);
    }
//	/**
//	 * 下载文件
//	 * 请求地址：http://localhost:8080/common/download/{user/20190119/e1fe9925bc315c60addea1b98eb1cb1349547719_1547866868179.jpg}
//	 *
//	 * @param request
//	 * @param response
//	 * @throws Exception
//	 */
//	@GetMapping(value = "/download/**")
//	public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
//		// ISO-8859-1 ==> UTF-8 进行编码转换
//		String filePath = extractPathFromPattern(request);
//		// 其余处理略
//		InputStream inputStream = null;
//		OutputStream outputStream = null;
//		try {
//			filePath = filePath.replace("..", "");
//			if (filePath.endsWith(",")) {
//				filePath = filePath.substring(0, filePath.length() - 1);
//			}
//			String localPath = uploadpath;
//			String downloadFilePath = localPath + File.separator + filePath;
//			File file = new File(downloadFilePath);
//	         if (file.exists()) {
//	         	response.setContentType("application/force-download");// 设置强制下载不打开            
//	 			response.addHeader("Content-Disposition", "attachment;fileName=" + new String(file.getName().getBytes("UTF-8"),"iso-8859-1"));
//	 			inputStream = new BufferedInputStream(new FileInputStream(file));
//	 			outputStream = response.getOutputStream();
//	 			byte[] buf = new byte[1024];
//	 			int len;
//	 			while ((len = inputStream.read(buf)) > 0) {
//	 				outputStream.write(buf, 0, len);
//	 			}
//	 			response.flushBuffer();
//	         }
//
//		} catch (Exception e) {
//			log.info("文件下载失败" + e.getMessage());
//			// e.printStackTrace();
//		} finally {
//			if (inputStream != null) {
//				try {
//					inputStream.close();
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
//			}
//			if (outputStream != null) {
//				try {
//					outputStream.close();
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
//			}
//		}
//
//	}

    /**
     * @功能：pdf预览Iframe
     * @param modelAndView
     * @return
     */
    @RequestMapping("/pdf/pdfPreviewIframe")
    public ModelAndView pdfPreviewIframe(ModelAndView modelAndView) {
        modelAndView.setViewName("pdfPreviewIframe");
        return modelAndView;
    }

    /**
     *  把指定URL后的字符串全部截断当成参数
     *  这么做是为了防止URL中包含中文或者特殊字符（/等）时，匹配不了的问题
     * @param request
     * @return
     */
    private static String extractPathFromPattern(final HttpServletRequest request) {
        String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        String bestMatchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
        return new AntPathMatcher().extractPathWithinPattern(bestMatchPattern, path);
    }

    /**
     * 中转HTTP请求，解决跨域问题
     *
     * @param url 必填：请求地址
     * @return
     */
    @RequestMapping("/transitRESTful")
    public Result transitRESTful(@RequestParam("url") String url, HttpServletRequest request) {
        try {
            ServletServerHttpRequest httpRequest = new ServletServerHttpRequest(request);
            // 中转请求method、body
            HttpMethod method = httpRequest.getMethod();
            JSONObject params;
            try {
                params = JSON.parseObject(JSON.toJSONString(httpRequest.getBody()));
            } catch (Exception e) {
                params = new JSONObject();
            }
            // 中转请求问号参数
            JSONObject variables = JSON.parseObject(JSON.toJSONString(request.getParameterMap()));
            variables.remove("url");
            // 在 headers 里传递Token
            String token = TokenUtils.getTokenByRequest(request);
            HttpHeaders headers = new HttpHeaders();
            headers.set("X-Access-Token", token);
            // 发送请求
            String httpURL = URLDecoder.decode(url, "UTF-8");
            ResponseEntity<String> response = RestUtil.request(httpURL, method, headers , variables, params, String.class);
            // 封装返回结果
            Result<Object> result = new Result<>();
            int statusCode = response.getStatusCodeValue();
            result.setCode(statusCode);
            result.setSuccess(statusCode == 200);
            String responseBody = response.getBody();
            try {
                // 尝试将返回结果转为JSON
                Object json = JSON.parse(responseBody);
                result.setResult(json);
            } catch (Exception e) {
                // 转成JSON失败，直接返回原始数据
                result.setResult(responseBody);
            }
            return result;
        } catch (Exception e) {
            log.debug("中转HTTP请求失败", e);
            return Result.error(e.getMessage());
        }
    }


}
